import logging
from datetime import datetime, timedelta
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp.util import run_wsgi_app
import bts
# Ensure indexes are configured
import indexes

logging.getLogger().setLevel(logging.INFO)

class IndexModel(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'
        key = self.request.get('key')
        force = bool(self.request.get('force'))
        model = db.get(key)
        if model:
            for index in model.__class__.bts_indexes:
                index.index(model, force=force)
            self.response.out.write('Indexed Model under key %s' % key)
        else:
            self.response.out.write('No Model found to index under key %s' % key
                    )

class AddTerms(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'
        terms = self.request.get('terms')
        key = self.request.get('key')
        model = db.get(key)
        index = bts.existing_indexes.get(self.request.get('index').lower(), None
                )
        if not index:
            logging.warn(
                    "No index found for name %s" % self.request.get('index'))
        if model and index:
            index.add(model, terms)
            self.response.out.write('Added Terms %s' % terms)
        else:
            self.response.out.write(
                    'No Model or Index found to index under key %s' % key)

class RemoveTerms(webapp.RequestHandler):
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'
        terms = self.request.get('terms')
        key = self.request.get('key')
        model = db.get(key)
        index = bts.existing_indexes.get(self.request.get('index').lower(), None
                )
        if not index:
            logging.warn(
                    "No index found for name %s" % self.request.get('index'))
        if model and index:
            index.remove(model, terms)
            self.response.out.write('Removed Terms %s' % terms)
        else:
            self.response.out.write(
                    'No Model or Index found to index under key %s' % key)

class CompactIndexes(webapp.RequestHandler):
    def get(self):
        start_time = datetime.now()
        for index in bts.existing_indexes.values():
            index.compact_inverted_index(start_time)
            index.compact_forward_index(start_time)
        self.response.out.write("Compacted indexes")

application = webapp.WSGIApplication([('/bts/index-model', IndexModel),
                                      ('/bts/add-terms', AddTerms),
                                      ('/bts/remove-terms', RemoveTerms),
                                      ('/bts/compact-indexes', CompactIndexes)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()